<template>
  <div class="article-list">
    <van-nav-bar
        title="健康科普"
        left-arrow
        @click-left="router.back()"
    />

    <!-- 文章分类 -->
    <van-tabs v-model:active="activeCategory" sticky @change="handleCategoryChange">
      <van-tab title="全部" name="0" />
      <van-tab
        v-for="category in categories"
        :key="category.id"
        :title="category.name"
        :name="category.id"
      />
    </van-tabs>

    <!-- 文章列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
      >
        <van-cell
            v-for="article in articles"
            :key="article.id"
            :title="article.title"
            is-link
            :to="`/article/${article.id}`"
        >
          <template #label>
            <div class="article-info">
              <span class="category" v-if="getCategoryName(article.categoryId)">
                {{ getCategoryName(article.categoryId) }}
              </span>
              <span class="time">{{ formatDateTime(article.createTime) }}</span>
            </div>
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getArticleList, getArticleCategories } from '@/api/article'
import { showToast } from 'vant'
import { formatDateTime } from '@/utils/format'

const router = useRouter()
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const articles = ref([])
const currentPage = ref(1)
const pageSize = 10
const categories = ref([])
const activeCategory = ref('0')

// 获取文章分类
const loadCategories = async () => {
  try {
    const { data } = await getArticleCategories()
    if (data && data.records) {
      categories.value = data.records
      console.log('文章分类:', categories.value)
    }
  } catch (error) {
    console.error('获取文章分类失败:', error)
    showToast('获取文章分类失败')
  }
}

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : ''
}

// 加载文章列表
const loadArticles = async () => {
  try {
    const params = {
      current: currentPage.value,
      size: pageSize
    }

    // 只有在选择了具体分类时才添加分类ID
    if (activeCategory.value !== '0') {
      params.categoryId = Number(activeCategory.value)
    }

    const { data } = await getArticleList(params)

    if (refreshing.value) {
      articles.value = []
      refreshing.value = false
    }

    if (data && data.records) {
      articles.value.push(...data.records)
      
      // 判断是否加载完成
      if (articles.value.length >= data.total) {
        finished.value = true
      } else {
        currentPage.value++
      }
    }
  } catch (error) {
    showToast('获取文章列表失败')
    console.error('获取文章列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 切换分类
const handleCategoryChange = () => {
  currentPage.value = 1
  finished.value = false
  articles.value = []
  loadArticles()
}

// 上拉加载
const onLoad = () => {
  loadArticles()
}

// 下拉刷新
const onRefresh = () => {
  finished.value = false
  currentPage.value = 1
  loadArticles()
}

onMounted(() => {
  loadCategories()
})
</script>

<style lang="scss" scoped>
.article-list {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;

  :deep(.van-tabs) {
    position: sticky;
    top: 46px;
    z-index: 10;
  }

  :deep(.van-cell) {
    padding: 12px 16px;

    .van-cell__title {
      flex: 1;
      margin-right: 12px;
    }

    .article-info {
      margin-top: 8px;
      display: flex;
      align-items: center;
      gap: 8px;

      .category {
        color: #1989fa;
        font-size: 12px;
        padding: 2px 6px;
        background-color: rgba(25, 137, 250, 0.1);
        border-radius: 4px;
      }

      .time {
        color: #999;
        font-size: 12px;
      }
    }
  }
}
</style>
